package com.cn.fw4j.util.rhino;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

public class JSField {
	private Scriptable scope;
	private String fieldName;
	
	public JSField(String inFieldName,Scriptable inScope){
		this.scope = inScope;
		this.fieldName = inFieldName;
	}
	
	public void set(Object val){
		scope.put(fieldName, scope, val);
	}
	
	public void javaToJs(Object value){
		Object obj = Context.javaToJS(value, scope);
		ScriptableObject.putProperty(scope, fieldName, obj);
	}
	
	public String get() throws Exception{
		Object obj = scope.get(fieldName, scope);
		if(obj == Scriptable.NOT_FOUND){
			Context.exit();
			throw new Exception("not found");
		}
		return Context.toString(obj);
	}
	
	public void exit(){
		Context.exit();
	}
}
